package fuzion24.device.vulnerability.vulnerabilities.framework.media;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import fuzion24.device.vulnerability.util.CPUArch;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
import fuzion24.device.vulnerability.vulnerabilities.helper.TestResult;

import static fuzion24.device.vulnerability.vulnerabilities.helper.BinaryAssets.extractAsset;
import static fuzion24.device.vulnerability.vulnerabilities.helper.CrashCheck.execute;

public class CVE_2015_6602 implements VulnerabilityTest {

    private static final String TAG = "cve-2015-6602";

    public CVE_2015_6602() {}

    @Override
    public List<CPUArch> getSupportedArchitectures() {
        ArrayList<CPUArch> archs = new ArrayList<>();
        archs.add(CPUArch.ARM7);
        archs.add(CPUArch.ARM);
        return archs;
    }

    @Override
    public String getCVEorID() {
        return "CVE-2015-6602";
    }

    @Override
    public boolean isVulnerable(Context context) throws Exception {
        String binaryTester = extractBinary(context);
        TestResult result = execute(context, 5, binaryTester);
        Log.d(TAG, "Test result: " + result.toString());
        if (result.isOk()) {
            return result.getCode() != 0;
        } else if (result == TestResult.CRASH) {
            return true;
        } else if (result == TestResult.HANG) {
            throw new Exception("Test is hanging");
        } else if (result == TestResult.ERROR) {
            throw new Exception("Test error");
        }
        throw new Exception("Unknown test result");
    }

    private String extractBinary(Context context) throws IOException {
        File dataDir = context.getFilesDir();

        final String extractedBinaryTester = dataDir.getAbsolutePath() + File.separator + getNativeAppName();
        extractAsset(context, "stagefright" + File.separator + getNativeAppName(),
                extractedBinaryTester);
        Process p = Runtime.getRuntime().exec("chmod 700 " + extractedBinaryTester);
        try { p.waitFor(); } catch (Exception e){}
        return extractedBinaryTester;
    }

    public static String getNativeAppName() {
        return "utilcheck-pie";
    }
}
